package com.peas.platform.module.icims.budget.project.domain.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.peas.platform.framework.mybatisplus.domain.BaseDomainImpl;
import com.peas.platform.framework.mybatisplus.repository.BaseRepository;
import com.peas.platform.module.icims.base.sys.service.SequenceService;
import com.peas.platform.module.icims.budget.project.adapter.repository.BudgetProjectOneRepository;
import com.peas.platform.module.icims.budget.project.adapter.repository.po.BudgetProjectOnePo;
import com.peas.platform.module.icims.budget.project.domain.BudgetProjectOneDomain;
import com.peas.platform.module.icims.budget.project.dto.BudgetProjectOneDto;
import com.peas.platform.module.icims.budget.project.dto.BudgetProjectTwoDto;
import com.peas.platform.module.icims.budget.project.service.BudgetProjectTwoService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

@Component
public class BudgetProjectOneDomainImpl extends BaseDomainImpl<BudgetProjectOneDto, BudgetProjectOnePo> implements BudgetProjectOneDomain {

    @Resource
    private BudgetProjectOneRepository budgetProjectOneRepository;
    @Resource
    private SequenceService sequenceService;
    @Resource
    private BudgetProjectTwoService budgetProjectTwoService;

    @Override
    public BaseRepository<BudgetProjectOnePo> getMapper() {
        return budgetProjectOneRepository;
    }

    @Override
    public Class<? extends BaseRepository<BudgetProjectOnePo>> getRepositoryClass() {
        return BudgetProjectOneRepository.class;
    }

    @Transactional
    @Override
    public int save(BudgetProjectOneDto dto) {
        if (StrUtil.isBlank(dto.getCode())) {
            String code = sequenceService.genSequence("budget", "BudgetProjectOneDto", "BPO", 4, 1);
            dto.setCode(code);
        }
        int result = super.save(dto);
        this.checkRepetition("code", dto.getCode());
        return result;
    }

    @Transactional
    @Override
    public int updateById(BudgetProjectOneDto dto) {
        int result = super.updateById(dto);
        this.checkRepetition("code", dto.getCode());
        return result;
    }

    @Transactional
    @Override
    public int removeById(Serializable id) {
        List<BudgetProjectTwoDto> list = budgetProjectTwoService.listByField("projectOneId", id);
        Assert.isTrue(CollUtil.isEmpty(list), "有关联的二级项目存在");
        return super.removeById(id);
    }

}
